﻿using Xc.DataAccess.Core.Extensions;
using System.Linq;
using System;
using System.Text.Json.Serialization;

namespace Xc.DataAccess.Protocoals.WaterMeters.Models
{
    /// <summary>
    /// 设备编号
    /// </summary>
    public struct DevcieId:IEquatable<DevcieId>
    {
        public DevcieId(byte[] hexValue)
        {
            HexValue = hexValue;
        }
        public override string ToString()
        {
            return BCDValue;
        }
        public static explicit operator DevcieId(string content)
        {
            return new DevcieId(content.ToHex());
        }
        /// <summary>
        /// HEX值
        /// </summary>

        [JsonIgnore]
        public byte[] HexValue { get;private set; }
        /// <summary>
        /// BCD值
        /// </summary>
        public string BCDValue
        {
            get
            {
                if (HexValue==null)
                {
                    return null;
                }
                return HexValue?.ToHex();
            }
        }

        /// <summary>
        /// 生产流水号
        /// </summary>
        public ushort? SerialNumber => HexValue?.Take(2).ToArray().ToUInt16LittleEndian();
        /// <summary>
        /// 厂商代码
        /// </summary>
        public ushort? FactoryNumber => HexValue?.Skip(4).Take(2).ToArray().ToUInt16LittleEndian();

        /// <summary>
        /// 生产年月日
        /// </summary>
        public Date? Date
        {
            get
            {
                if (Date == null)
                {
                    return null;
                }
                return new Date( HexValue.Skip(2).Take(2).ToArray());
            }
        }

        public bool Equals(DevcieId other)
        {
            return this.BCDValue == other.BCDValue;
        }
    }
}